#include "mystdio.h"
char* ToString(int fls)
{
	if(fls & NONE_FLUSH)return "None";
	if(fls & LINE_FLUSH)return "Line";
	if(fls & FULL_FLUSH)return "Full";

	return "unknow flash mode";
}
void DebugPrint(my_FILE* pf)
{
	printf("buffer:%s\n",pf->_buffer);
	printf("fd:%d\n",pf->_fileNo);
	printf("flush_mode:%s\n",ToString(pf->_flush));
}
my_FILE* my_fopen(const char* filename,const char* mode)
{
	int flag = 0;
	if(strcmp(mode,"r") == 0)
	{
		flag |= O_RDONLY;
	}
	else if(strcmp(mode,"w")==0)
	{
		flag |= (O_WRONLY | O_CREAT | O_TRUNC);
	}
	else if(strcmp(mode,"a") ==0)
	{
		flag |= (O_WRONLY | O_CREAT | O_APPEND);
	}
	else {
		return NULL;
	}
	int _fd = 0;
	if(flag & O_WRONLY)
	{
		umask(0);
		_fd = open(filename,flag,0666);
	}
	else
	{
		_fd = open(filename,flag);
	}
	//
	if(_fd < 0) return NULL;
	my_FILE* pf = (my_FILE*)malloc(sizeof(my_FILE));
	pf->_fileNo = _fd;
	pf->_pos = 0;
	pf->_cap = SIZE;
	pf->_flush = LINE_FLUSH;
	return pf;
}
void my_fflush(my_FILE* pf)
{
	if(pf->_pos == 0)return;
	write(pf->_fileNo,pf->_buffer,pf->_pos);
	pf->_pos = 0;
}
void my_close(my_FILE* pf)
{
	my_fflush(pf);
	close(pf->_fileNo);
	free(pf);
}
int my_fwrite(const char* s,size_t size,size_t n,my_FILE* pf)
{
	//写入
	memcpy(pf->_buffer+pf->_pos,s,size);
	pf->_pos += size;
	//刷新
	if(pf->_flush & LINE_FLUSH && (pf->_buffer[pf->_pos-1] == '\n'))
	{
		my_fflush(pf);
	}
	else if(pf->_flush & FULL_FLUSH && (pf->_pos == pf->_cap))
	{
		my_fflush(pf);
	}
	else{
	}

	return size;
}
